package com.jingxi.sso.service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.jingxi.common.pojo.JingXiResult;
import com.jingxi.common.util.CookieUtils;
import com.jingxi.common.util.JsonUtils;
import com.jingxi.mapper.TbUserMapper;
import com.jingxi.model.TbUser;
import com.jingxi.model.TbUserExample;
import com.jingxi.model.TbUserExample.Criteria;
import com.jingxi.sso.dao.JedisClient;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private TbUserMapper tbUserMapper;

	@Autowired
	private JedisClient jedisClient;

	@Value("${REDIS_USER_SESSION_KEY}")
	private String REDIS_USER_SESSION_KEY;

	@Value("${SSO_SESSION_EXPIRE}")
	private Integer SSO_SESSION_EXPIRE;

	private static final int USER_EXISTED = 11;
	private static final int USER_CANUSE = 12;
	private static final int ERROR_FORMAT = 13;
	private static final int RIGHT_FORMAT = 14;

	@Override
	public JingXiResult checkData(String content, Integer type) {
		// 创建查询条件
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();

		// type为数据类型，1、2分别代表username、password
		if (type == 1) {
			// 用户名验证
			String regExp = "[0-9A-Za-z]{3,8}";
			if (!content.matches(regExp)) {
				return JingXiResult.ok(ERROR_FORMAT);
			} else {
				// 判断用户是否存在与数据库
				criteria.andUsernameEqualTo(content);
				List<TbUser> list = tbUserMapper.selectByExample(example);
				if (list.isEmpty()) {
					return JingXiResult.ok(USER_CANUSE);
				}
				return JingXiResult.ok(USER_EXISTED);
			}
		}
		if (type == 2) {
			// 密码验证
			String regExp = "[0-9A-Za-z\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\-\\=\\_\\+\\/{}<>,|\\.\\?;\"\\:']{6,12}";
			if (!content.matches(regExp)) {
				return JingXiResult.ok(ERROR_FORMAT);
			}
			return JingXiResult.ok(RIGHT_FORMAT);
		}
		return JingXiResult.ok(RIGHT_FORMAT);
	}

	@Override
	public JingXiResult createUser(TbUser user) {
		JingXiResult userResult = checkData(user.getUsername(), 1);
		JingXiResult pwdResult = checkData(user.getPassword(), 2);
		if (Integer.parseInt(userResult.getData().toString()) == USER_CANUSE
				&& Integer.parseInt(pwdResult.getData().toString()) == RIGHT_FORMAT) {
			Date date = new Date();
			user.setCreated(date);
			user.setUpdated(date);
			user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
			tbUserMapper.insert(user);
			return JingXiResult.ok(true);
		}

		return JingXiResult.ok(false);
	}

	@Override
	public JingXiResult userLogin(String username, String password, HttpServletRequest request,
			HttpServletResponse response) {

		TbUserExample example = new TbUserExample();

		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);

		List<TbUser> list = tbUserMapper.selectByExample(example);

		if (null == list || list.isEmpty()) {
			return JingXiResult.build(400, "用户名或密码错误");
		}
		TbUser user = list.get(0);
		// 验证密码
		if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
			return JingXiResult.build(400, "用户名或密码错误");
		}
		// 生成token
		String token = UUID.randomUUID().toString();

		user.setPassword(null);
		// 把用户信息写入缓存
		jedisClient.set(REDIS_USER_SESSION_KEY + ":" + token, JsonUtils.objectToJson(user));
		jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);

		// 登录成功后将token写到cookie， 默认的有效期是关闭浏览器失效
		CookieUtils.setCookie(request, response, "TT_TOKEN", token);
		System.out.println("写入Cookie" + token + ":" + getUserByToken(token));
		
		request.getSession().setAttribute("TT_TOKEN", token);
		// 返回结果
		return JingXiResult.ok(token);
	}

	@Override
	public JingXiResult getUserByToken(String token) {
		String json = jedisClient.get(REDIS_USER_SESSION_KEY + ":" + token);

		if (StringUtils.isBlank(json)) {
			return JingXiResult.build(400, "session已过期，请重新登录");
		}

		TbUser tbUser = JsonUtils.jsonToObject(json, TbUser.class);
		return JingXiResult.ok(tbUser);
	}

	@Override
	public JingXiResult quitWithSafety(String token) {
		String json = jedisClient.get(REDIS_USER_SESSION_KEY + ":" + token);
		if (StringUtils.isBlank(json)) {
			return JingXiResult.build(400, "session已过期，请重新登录");
		}
		jedisClient.del(REDIS_USER_SESSION_KEY + ":" + token);
		return JingXiResult.ok();
	}

}
